<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>综合监控系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
            padding: 20px;
        }
        
        .tabs {
            display: flex;
            margin-bottom: 20px;
            border-bottom: 1px solid #ddd;
        }
        
        .tab {
            padding: 10px 20px;
            cursor: pointer;
            background-color: #f1f1f1;
            margin-right: 5px;
            border-radius: 5px 5px 0 0;
        }
        
        .tab.active {
            background-color: white;
            border-bottom: 2px solid #3498db;
        }
        
        .tab-content {
            display: none;
        }
        
        .tab-content.active {
            display: block;
        }
        
        .device-panel {
            background-color: white;
            border-radius: 5px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        
        .device-panel h2 {
            margin-bottom: 15px;
            color: #2c3e50;
        }
        
        .sensor-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 15px;
        }
        
        .sensor-item {
            background-color: #f9f9f9;
            padding: 15px;
            border-radius: 5px;
            border-left: 4px solid #3498db;
        }
        
        .value-display {
            font-size: 24px;
            font-weight: bold;
            color: #3498db;
        }
        
        .control-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px;
            background-color: #f9f9f9;
            border-radius: 5px;
            margin-bottom: 10px;
        }
        
        .control-item button {
            padding: 5px 10px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
        }
        
        .control-item button:hover {
            background-color: #2980b9;
        }
        
        .status-message {
            margin-top: 20px;
            padding: 10px;
            border-radius: 5px;
            text-align: center;
        }
        
        .error {
            background-color: #ffebee;
            color: #c62828;
        }
        
        .success {
            background-color: #e8f5e9;
            color: #2e7d32;
        }
        
        .video-container {
            width: 100%;
            min-height: 300px;
            background-color: #333;
            border-radius: 5px;
            display: flex;
            justify-content: center;
            align-items: center;
            color: white;
            margin-bottom: 20px;
            overflow: hidden;
            position: relative;
        }
        
        .video-frame {
            max-width: 100%;
            max-height: 100%;
            border: none;
            display: block;
            margin: 0 auto;
        }
        
        .video-controls {
            text-align: center;
            margin-top: 10px;
        }
        
        .video-controls button {
            padding: 8px 15px;
            margin: 0 5px;
            background-color: #3498db;
            color: white;
            border: none;
            border-radius: 3px;
            cursor: pointer;
        }
        
        .video-controls button:hover {
            background-color: #2980b9;
        }
        
        .toggle-buttons {
            display: flex;
            gap: 5px;
        }
        
        .toggle-buttons button {
            padding: 5px 10px;
        }
        
        .toggle-buttons button.active {
            background-color: #2ecc71;
        }
        
        .modbus-control {
            display: grid;
            grid-template-columns: repeat(2, 1fr);
            gap: 15px;
        }
        
        .modbus-device {
            background-color: #f0f7ff;
            padding: 15px;
            border-radius: 5px;
            border-left: 4px solid #5d9cec;
        }
        
        .modbus-device h3 {
            margin-top: 0;
            color: #3a7bb8;
        }
        
        .modbus-status {
            font-size: 18px;
            margin: 10px 0;
        }
        
        .modbus-buttons {
            display: flex;
            gap: 10px;
        }
        
        .modbus-buttons button {
            flex: 1;
        }
        
        .modbus-sensor-value {
            font-size: 24px;
            font-weight: bold;
            color: #3a7bb8;
            text-align: center;
            margin: 10px 0;
        }
        
        .debug-info {
            font-size: 12px;
            color: #666;
            margin-top: 5px;
            padding: 5px;
            background-color: #f9f9f9;
            border-radius: 3px;
        }
    </style>
</head>
<body>
    <div class="tabs">
        <div class="tab active" onclick="switchTab('stm32-tab')">STM32监控</div>
        <div class="tab" onclick="switchTab('modbus-tab')">Modbus监控</div>
        <div class="tab" onclick="switchTab('video-tab')">视频监控</div>
    </div>
    
    <!-- STM32监控界面 -->
    <div id="stm32-tab" class="tab-content active">
        <div class="device-panel">
            <h2>传感器数据（按STM key值映射）</h2>
            <div class="sensor-grid">
                <div class="sensor-item">
                    <p>温度（key=1，double）</p>
                    <div class="value-display" id="temperature">--°C</div>
                </div>
                <div class="sensor-item">
                    <p>湿度（key=2，double）</p>
                    <div class="value-display" id="humidity">--%</div>
                </div>
                <div class="sensor-item">
                    <p>红色LED（key=3）</p>
                    <div class="value-display" id="red_light">--</div>
                </div>
                <div class="sensor-item">
                    <p>火焰传感器（key=4）</p>
                    <div class="value-display" id="fire-sensor">--</div>
                </div>
            </div>
        </div>
        
        <div class="device-panel">
            <h2>控制设备（与STM指令对应）</h2>
            <div class="control-item">
                <p>风扇（key=5）</p>
                <div class="toggle-buttons">
                    <button id="fan-on" onclick="sendStmCommand('FAN_ON', 'fan')">开启</button>
                    <button id="fan-off" onclick="sendStmCommand('FAN_OFF', 'fan')">关闭</button>
                </div>
                <div class="value-display" id="fan">--</div>
            </div>
            <div class="control-item">
                <p>窗户（电机，key=6）</p>
                <div class="toggle-buttons">
                    <button id="motor-on" onclick="sendStmCommand('MOTOR_ON', 'window')">开启</button>
                    <button id="motor-off" onclick="sendStmCommand('MOTOR_OFF', 'window')">关闭</button>
                </div>
                <div class="value-display" id="window">--</div>
            </div>
            <div class="control-item">
                <p>灯光（key=7）</p>
                <div class="toggle-buttons">
                    <button id="ld1-on" onclick="sendStmCommand('LD1_ON', 'light')">开启</button>
                    <button id="ld1-off" onclick="sendStmCommand('LD1_OFF', 'light')">关闭</button>
                </div>
                <div class="value-display" id="light">--</div>
            </div>
            <div class="control-item">
                <p>蜂鸣器（key=8）</p>
                <div class="toggle-buttons">
                    <button id="beep-on" onclick="sendStmCommand('BEEP_ON', 'buzzer')">开启</button>
                    <button id="beep-off" onclick="sendStmCommand('BEEP_OFF', 'buzzer')">关闭</button>
                </div>
                <div class="value-display" id="buzzer">--</div>
            </div>
            <div class="control-item">
                <p>火焰指示灯（LD3，key=4关联）</p>
                <div class="toggle-buttons">
                    <button id="ld3-on" onclick="sendStmCommand('LD3_ON', 'fire-led')">开启</button>
                    <button id="ld3-off" onclick="sendStmCommand('LD3_OFF', 'fire-led')">关闭</button>
                </div>
                <div class="value-display" id="fire-led">--</div>
            </div>
        </div>
    </div>
    
    <!-- Modbus监控界面 -->
    <div id="modbus-tab" class="tab-content">
        <div class="device-panel">
            <h2>Modbus传感器数据（与Modbus代码key对应）</h2>
            <div class="sensor-grid">
                <div class="sensor-item">
                    <p>人流量（key=101）</p>
                    <div class="value-display" id="people-flow">--</div>
                    <div class="debug-info">int类型数据</div>
                </div>
                <div class="sensor-item">
                    <p>空调温度（key=105）</p>
                    <div class="value-display" id="air-temp">--°C</div>
                    <div class="debug-info">double类型数据</div>
                </div>
            </div>
        </div>
        
        <div class="device-panel">
            <h2>Modbus设备控制（与Modbus代码key对应）</h2>
            <div class="modbus-control">
                <div class="modbus-device">
                    <h3>门磁（key=102）</h3>
                    <div class="modbus-status" id="door-status">状态: --</div>
                    <div class="modbus-buttons">
                        <button onclick="sendModbusCommand('door', 1)">开启</button>
                        <button onclick="sendModbusCommand('door', 0)">关闭</button>
                    </div>
                    <div class="debug-info">bool类型数据</div>
                </div>
                
                <div class="modbus-device">
                    <h3>窗户（key=103）</h3>
                    <div class="modbus-status" id="window-status">状态: --</div>
                    <div class="modbus-buttons">
                        <button onclick="sendModbusCommand('window', 1)">开启</button>
                        <button onclick="sendModbusCommand('window', 0)">关闭</button>
                    </div>
                    <div class="debug-info">bool类型数据</div>
                </div>
                
                <div class="modbus-device">
                    <h3>空调开关（key=104）</h3>
                    <div class="modbus-status" id="ac-status">状态: --</div>
                    <div class="modbus-buttons">
                        <button onclick="sendModbusCommand('ac', 1)">开启</button>
                        <button onclick="sendModbusCommand('ac', 0)">关闭</button>
                    </div>
                    <div class="debug-info">bool类型数据</div>
                </div>
                
                <div class="modbus-device">
                    <h3>风扇（key=106）</h3>
                    <div class="modbus-status" id="fan-status">状态: --</div>
                    <div class="modbus-buttons">
                        <button onclick="sendModbusCommand('fan', 1)">开启</button>
                        <button onclick="sendModbusCommand('fan', 0)">关闭</button>
                    </div>
                    <div class="debug-info">bool类型数据</div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 视频监控界面 -->
    <div id="video-tab" class="tab-content">
        <div class="device-panel">
            <h2>视频监控</h2>
            <div class="video-container">
                <iframe id="video-stream" class="video-frame" src="http://192.168.31.161:8080/?action=stream" onload="adjustVideoSize()"></iframe>
            </div>
            <div class="video-controls">
                <button onclick="refreshVideoStream()">刷新视频流</button>
                <button onclick="captureImage()">拍照</button>
                <button onclick="toggleFullscreen()">全屏</button>
            </div>
        </div>
    </div>
    
    <div id="status-message" class="status-message" style="display: none;"></div>
    
    <script>
        // 切换标签页
        function switchTab(tabId) {
            document.querySelectorAll('.tab-content').forEach(content => {
                content.classList.remove('active');
            });
            document.querySelectorAll('.tab').forEach(tab => {
                tab.classList.remove('active');
            });
            document.getElementById(tabId).classList.add('active');
            event.currentTarget.classList.add('active');
            
            if (tabId === 'video-tab') {
                refreshVideoStream();
            }
            if (tabId === 'modbus-tab') {
                fetchModbusData();
            }
        }

        // 调整视频大小
        function adjustVideoSize() {
            const videoContainer = document.querySelector('.video-container');
            const videoFrame = document.getElementById('video-stream');
            
            try {
                const videoWidth = videoFrame.contentWindow.document.body.scrollWidth;
                const videoHeight = videoFrame.contentWindow.document.body.scrollHeight;
                const containerWidth = videoContainer.clientWidth;
                const containerHeight = videoContainer.clientHeight;
                
                let widthRatio = containerWidth / videoWidth;
                let heightRatio = containerHeight / videoHeight;
                let scale = Math.min(widthRatio, heightRatio);
                
                videoFrame.style.width = (videoWidth * scale) + 'px';
                videoFrame.style.height = (videoHeight * scale) + 'px';
            } catch (e) {
                videoFrame.style.width = '100%';
                videoFrame.style.height = 'auto';
            }
        }

        // 刷新视频流
        function refreshVideoStream() {
            const videoElement = document.getElementById('video-stream');
            showStatus("正在刷新视频流...", false);
            const timestamp = new Date().getTime();
            videoElement.src = 'about:blank';
            setTimeout(() => {
                videoElement.src = `http://192.168.31.161:8080/?action=stream&t=${timestamp}`;
            }, 100);
        }

        // 拍照功能
        function captureImage() {
            const videoFrame = document.getElementById('video-stream');
            const canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            
            try {
                canvas.width = videoFrame.clientWidth;
                canvas.height = videoFrame.clientHeight;
                ctx.drawImage(videoFrame, 0, 0, canvas.width, canvas.height);
                const image = canvas.toDataURL('image/jpeg');
                const link = document.createElement('a');
                link.download = 'capture_' + new Date().getTime() + '.jpg';
                link.href = image;
                link.click();
                showStatus('拍照成功！', false);
            } catch (e) {
                showStatus('拍照失败: 可能由于跨域限制', true);
            }
        }

        // 全屏切换
        function toggleFullscreen() {
            const videoContainer = document.querySelector('.video-container');
            if (!document.fullscreenElement) {
                videoContainer.requestFullscreen().catch(err => {
                    console.error(`全屏错误: ${err.message}`);
                });
            } else {
                document.exitFullscreen();
            }
        }

        // 发送STM命令
        async function sendStmCommand(command, elementId) {
            try {
                const response = await fetch(`http://localhost:8081/stm/control`, {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({command: command})
                });
                
                if (!response.ok) {
                    throw new Error(`状态码: ${response.status}`);
                }
                
                const result = await response.json();
                showStatus(`命令 ${command} 已发送至STM`, false);
                await fetchSTM32Data();
                updateButtonStates();
                
            } catch (error) {
                showStatus(`发送命令失败: ${error.message}`, true);
            }
        }

        // 发送Modbus命令
        async function sendModbusCommand(device, state) {
            try {
                const response = await fetch(`http://localhost:8081/modbus/control`, {
                    method: 'POST',
                    headers: {'Content-Type': 'application/json'},
                    body: JSON.stringify({device: device, state: state})
                });
                
                if (!response.ok) {
                    throw new Error(`状态码: ${response.status}`);
                }
                
                showStatus(`Modbus设备 ${device} 已${state ? '开启' : '关闭'}`, false);
                await fetchModbusData();
                
            } catch (error) {
                showStatus(`控制失败: ${error.message}`, true);
            }
        }

        // 更新按钮状态
        function updateButtonStates() {
            document.querySelectorAll('.toggle-buttons button').forEach(btn => btn.classList.remove('active'));
            
            const fanState = document.getElementById('fan').textContent;
            const lightState = document.getElementById('light').textContent;
            const windowState = document.getElementById('window').textContent;
            const buzzerState = document.getElementById('buzzer').textContent;
            const fireLedState = document.getElementById('fire-led').textContent;
            
            if (fanState === '开启') document.getElementById('fan-on').classList.add('active');
            else if (fanState === '关闭') document.getElementById('fan-off').classList.add('active');
            
            if (lightState === '开启') document.getElementById('ld1-on').classList.add('active');
            else if (lightState === '关闭') document.getElementById('ld1-off').classList.add('active');
            
            if (windowState === '开启') document.getElementById('motor-on').classList.add('active');
            else if (windowState === '关闭') document.getElementById('motor-off').classList.add('active');
            
            if (buzzerState === '开启') document.getElementById('beep-on').classList.add('active');
            else if (buzzerState === '关闭') document.getElementById('beep-off').classList.add('active');
            
            if (fireLedState === '开启') document.getElementById('ld3-on').classList.add('active');
            else if (fireLedState === '关闭') document.getElementById('ld3-off').classList.add('active');
        }

        // 状态提示
        function showStatus(message, isError) {
            const el = document.getElementById('status-message');
            el.textContent = message;
            el.className = isError ? 'status-message error' : 'status-message success';
            el.style.display = 'block';
            setTimeout(() => el.style.display = 'none', 3000);
        }

        // 获取STM数据
        async function fetchSTM32Data() {
            try {
                const response = await fetch('http://localhost:8081/stm/data');
                if (!response.ok) throw new Error(`状态码: ${response.status}`);
                const data = await response.json();
                
                // 更新传感器显示
                updateDisplay('temperature', data.devices.temperature, '°C', true);
                updateDisplay('humidity', data.devices.humidity, '%', true);
                updateDisplay('red_light', data.devices.red_light, '', false);
                updateDisplay('fire-sensor', data.devices.fire, '', false);
                
                // 更新控制设备显示
                updateDisplay('fan', data.devices.fan, '', false);
                updateDisplay('window', data.devices.window, '', false);
                updateDisplay('light', data.devices.light, '', false);
                updateDisplay('buzzer', data.devices.buzzer, '', false);
                updateDisplay('fire-led', data.devices.red_light, '', false);
                
                updateButtonStates();
                
            } catch (error) {
                console.error("STM数据获取失败:", error);
                showStatus(`获取STM数据失败: ${error.message}`, true);
            }
        }

        // 核心修改：获取Modbus数据并更新UI
        async function fetchModbusData() {
            try {
                console.log("请求Modbus数据的URL：", 'http://localhost:8081/modbus/data');
                const response = await fetch('http://localhost:8081/modbus/data');
                if (!response.ok) {
                    throw new Error(`HTTP状态码: ${response.status}`);
                }
                
                const data = await response.json();
                console.log("获取到Modbus数据:", data);
                
                // 更新传感器数据（处理默认值）
                updateDisplay('people-flow', data.people_flow, '', true);
                updateDisplay('air-temp', data.air_temp, '°C', true);
                
                // 更新设备状态（处理默认值）
                updateModbusDeviceStatus('door-status', data.door);
                updateModbusDeviceStatus('window-status', data.window);
                updateModbusDeviceStatus('ac-status', data.ac);
                updateModbusDeviceStatus('fan-status', data.fan);
                
            } catch (error) {
                console.error("Modbus数据获取失败:", error);
                showStatus(`获取Modbus数据失败: ${error.message}`, true);
            }
        }

        // 更新Modbus设备状态显示
        function updateModbusDeviceStatus(elementId, state) {
            const el = document.getElementById(elementId);
            if (!el) return;
            
            // 处理未获取到数据的情况
            if (state === -1) {
                el.textContent = "状态: 未知";
                return;
            }
            
            // 显示状态文本
            const statusText = state === 1 ? "开启" : "关闭";
            el.textContent = `状态: ${statusText}`;
            
            // 更新按钮激活状态
            const buttons = el.nextElementSibling.querySelectorAll('button');
            buttons[0].classList.toggle('active', state === 1);  // 开启按钮
            buttons[1].classList.toggle('active', state === 0);  // 关闭按钮
        }

        // 更新显示内容（统一处理默认值）
        function updateDisplay(elementId, value, unit, isNumeric) {
            const el = document.getElementById(elementId);
            if (!el) return;
            
            // 处理未获取到数据的情况
            if (value === null || value === undefined || value === -1) {
                el.textContent = `--${unit}`;
                return;
            }
            
            // 数值型数据（保留一位小数）
            if (isNumeric) {
                if (typeof value === 'number') {
                    el.textContent = `${value.toFixed(1)}${unit}`;
                } else {
                    el.textContent = `${value}${unit}`;
                }
            } 
            // 状态型数据（转换为文字）
            else {
                const stateText = value === 1 ? "开启" : "关闭";
                el.textContent = stateText;
            }
        }

        // 定时刷新数据
        setInterval(fetchSTM32Data, 2000);
        setInterval(fetchModbusData, 1000);  // 每秒刷新一次Modbus数据
        
        // 页面加载时初始化
        window.onload = () => {
            fetchSTM32Data();
            fetchModbusData();
            window.addEventListener('resize', adjustVideoSize);
        };
    </script>
</body>
</html>